package com.itts.Factory;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.GenericTypeResolver;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class ValidatoryFactory implements ApplicationContextAware {

    private static Map<String, Validator> map = new HashMap<>();
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Validator> all = applicationContext.getBeansOfType(Validator.class);
        for (Validator converter : all.values()) {
            Class<?>[] aClass = GenericTypeResolver.resolveTypeArguments(converter.getClass(), Validator.class);
            StringBuilder builder = new StringBuilder();
            for (Class<?> aClass1 : aClass) {
                builder.append(aClass1.getCanonicalName());
            }
            map.put(builder.toString(), converter);
        }
    }

    public static <T> Validator<T> getValidator(Class<T> source){
        return map.get(source.getCanonicalName());
    }


}
